<template>

  <el-dialog
    top="20px"
    :title="defaultValue.title"
    :lock-scroll="tableConfig.lockScroll"
    :append-to-body="tableConfig.appendToBody"
    :visible="tableConfig.show"
    @close="tableConfig.show = false"
    :show-close="tableConfig.showClose"
    :destroy-on-close="tableConfig.destroyOnClose"
    width="1260px">

    <!--列表-->
    <div class="list-peripheral">
      <div class="list-content" v-for="(obj, index) in this.wordList" :key="obj.id">
        <el-row>
          <el-col :span="6" class="list-images-shell">
            <img class="list-images" :src="randomImages()" alt=""/>
          </el-col>
          <el-col :span="18">
            <div class="list-content-shell">
              {{obj.word}}

              <div class="list-content-shell-more">
                <el-dropdown>
                  <span class="el-dropdown-link">
                    更多
                    <!--<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="readWordTips(obj)">朗读</el-dropdown-item>
                    <el-dropdown-item @click.native="updWordTips(obj)">编辑</el-dropdown-item>
                    <el-dropdown-item @click.native="delWordTips(obj)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </div>
            <div class="list-chineseMeaning">
              {{obj.chineseMeaning}}
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <span slot="footer" >
      <el-button plain type="warning" @click="saveWordTips" >新增单词</el-button>
      <el-button plain type="warning" @click="readWord" >朗读全部</el-button>
      <el-button plain type="primary" @click="tableConfig.show = false">关闭</el-button>
    </span>


  </el-dialog>

</template>

<script>

  import http from '@/utils/http'
  import {clearInvalid} from "../../utils/utils";

  export default {
    name: "WordList",
    data(){
      return {
        // 默认值，进入页面后的值
        defaultValue: {
          // 弹出框标题
          title: '单词列表',
          // 保存还是修改or查看,取值有 select | save | upd
          saveUpdSelect: 'select'
        },
        // 表格的默认值
        tableConfig: {
          // 关闭时销毁 Dialog 中的元素
          destroyOnClose: true,
          // 弹出框是否打开
          show: false,
          // 是否显示关闭按钮
          showClose: true,
          // 下面2个属性解决打开弹出框后没有在最上面显示的问题，导致看到的内容是一半的，需要先将滚动条移到最上面
          lockScroll: false,
          appendToBody: true,
        },
        // 要提交的数据
        wordGroupId: null,
        // 单词数据
        wordList: [],
        // 播放标记,false 没有播放
        playFlag: false,
      }
    },
    methods: {
      /**
       * 朗读全部的单词
       */
      readWord(){
        if (this.wordList === null || this.wordList.length === 0){
          this.$message.error("没有需要朗读的单词");
          return
        }
        // let playerArray = []
        // for (let obj of this.wordList){
        //   let player = new Audio(obj.pronunciation);
        //   playerArray.push(player)
        // }

        let index = -1
        this.playVoice(index)
      },
      /**
       * 声音播放,循环播放
       * @param playerArray 要播放的列表
       * @param index 索引，读到什么位置了
       */
      playVoice(index){
        index ++
        if (index === this.wordList.length){
          return
        }
        let wordObj = this.wordList[index]
        let player = new Audio(wordObj.pronunciation)
        // 增加监听事件，完成了才调用下一个
        player.addEventListener('ended', () => {
          this.playVoice(index)
        });

        this.$notify({
          title: wordObj.word,
          message: wordObj.chineseMeaning
        });

        // 播放
        player.play()
      },
      /**
       * 朗读
       * @param obj 要读的单词
       */
      readWordTips(obj){
        let player = new Audio(obj.pronunciation);
        player.play();
      },
      /**
       * 删除前的提示
       * @param obj 要删除的对象
       */
      delWordTips(obj){
        this.$confirm('是否删除该单词, 删除后无法恢复，是否继续?', '提示', {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消删除',
          type: 'warning'
        }).then(() => {
          // 确定删除
          this.delWord(obj)

        }).catch(() => {
          // 取消删除
        });
      },
      /**
       * 删除单词
       * @param obj 单词对象
       */
      delWord(obj){
        http.post("/word/delWord", {
          id: obj.id,
        }).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }
          this.getWordByWordGroupId()
          this.$message.success("删除成功");

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 更新前弹出框
       */
      updWordTips(obj){
        this.$prompt(' ', '请输入英语单词', {inputValue:  `${obj.word}`
          // action 是操作的类型，比如这里是确认，value 是输入框中的值
        }).then(({ value, action }) => {
          if(!value){
            return false;
          }
          obj.word = value
          this.updWord(obj)
        })
      },
      /**
       * 更新单词
       */
      updWord(obj){
        clearInvalid(obj)
        http.post("/word/updWord", obj).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }
          this.getWordByWordGroupId()
          this.$message.success("更新成功");

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 随机显示图片
       */
      randomImages(){
        // 图标借鉴了 https://www.goto-mars.com/people/L1AYO1a87O
        let random = 1 + Math.floor(Math.random() * Math.random() * 20)
        return require('@/assets/images/word/' + random + '.png')
      },
      /**
       * 打开弹出框
       * @param wordGroupId 单词组ID
       */
      openBeforeWordPage(wordGroupId){
        this.wordGroupId = wordGroupId
        this.getWordByWordGroupId()
        this.tableConfig.show = true
      },
      /**
       * 新增单词
       */
      saveWordTips(){
        this.$prompt('请输入英语单词', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          // inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
          // inputErrorMessage: '邮箱格式不正确'
        }).then(({ value }) => {
          this.saveWord(value.trim())

        }).catch(() => {
          // 取消
        });
      },
      /**
       * 保存单词
       * @param word 单词
       */
      saveWord(word){
        http.post("/word/saveWord", {
          word: word,
          wordGroupId: this.wordGroupId
        }).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }
          this.getWordByWordGroupId()
          this.$message.success("保存成功");

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
      /**
       * 根据单词组ID查询单词
       */
      getWordByWordGroupId(){
        http.post("/word/getWordByWordGroupId", {
          wordGroupId: this.wordGroupId
        }).then(response => {
          let res = response.data;
          if (res.status === 'error'){
            // 401是token过期跳转的
            if (res.code !== 401){
              this.$message.error(res.msg);
            }
            return
          }
          this.wordList = res.data

        }).catch(error => {
          this.$message.error(error.message);
        })
      },
    },
    mounted(){

    },
  }
</script>

<style scoped>

  .list-content {
    /*width: 230px;*/
    /*height: 70px;*/
    width: 200px;
    height: 60px;
    border: 1px solid #e2e2e2;
    margin: 9px 18px;
    overflow:hidden;
    float: left;
  }

  .list-peripheral {
    max-height: 600px;
    height: 600px;
    /*text-align: center;*/
    /*设置为浮动，可以一直往下排*/
    /*display: flex;*/
    /*flex-wrap: wrap;*/

    /*让子div居中*/
    justify-content: center;
    align-items:center;
    /*超过最大则显示滚动条*/
    overflow-y: scroll;
    /*overflow:hidden;*/
  }

  /*.list-content:hover{*/
  /*  cursor:pointer;*/
  /*  !*鼠标移动上来，缓慢向上移动*!*/
  /*  transform: translateY(-5px);*/
  /*  transition: all .5s;*/
  /*}*/

  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
    font-size: 10px;
  }

  .list-images-shell {
    line-height:80px;
    text-align: center
  }

  .list-images {
    width: 32px;
    height: 32px;
  }

  .list-content-shell {
    font-weight:600;
    margin-top: 5px;
  }

  .list-content-shell-more{
    float:right;
    margin-right:10px;
  }

  .list-chineseMeaning {
    color: #999;
    font-size: 12px;
  }

</style>
